package lab;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class Lab15 {
	public static void main(String[] args) throws Exception {
		byte[] data = HexStrToBytes("BD10365A51BF3046");
		byte[] key = HexStrToBytes("3684A2FD9C7EBA86");
		
		System.out.println(BytesToHexStr(decrypt(data, key)));
	}
	
	/**
	 * DES解密，ECB模式，无填充
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
		Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
		SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = factory.generateSecret(new DESKeySpec(key));
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		return cipher.doFinal(data);
	}

	/**
	 * DES加密，ECB模式，无填充
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
		Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
		SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = factory.generateSecret(new DESKeySpec(key));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		return cipher.doFinal(data);
	}
	
	/**
	 * 十六进制字符串转化为字节数组
	 * @param hexStr
	 * @return
	 * @throws Exception
	 */
	public static byte[] HexStrToBytes(String hexStr) throws Exception{
		if(hexStr.length() % 2 != 0){
			throw new Exception("输入有误！");
		}
		
		byte[] bytes = new byte[hexStr.length() / 2];
		for(int i = 0; i < bytes.length; i++){
			bytes[i] = (byte)Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
		}
		
		return bytes;
	}
	
	private static final String[] HEX_STR = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
	
	/**
	 * 字节数组转化十六进制字符串
	 * @param bytes
	 * @return
	 */
	public static String BytesToHexStr(byte[] bytes){
		StringBuilder sb = new StringBuilder();
		
		for(byte b : bytes){
			sb.append(HEX_STR[(b >> 4) & 0x0f]).append(HEX_STR[b & 0x0f]);
		}
		
		return sb.toString();
	}
}
